package p.ithorns.integration.zk.id;



/**
 * IdFlatter
 * TODO
 *
 * @author ithorns
 * @version 1.0
 * @date 2021/9/8 19:05
 */
@SuppressWarnings("Duplicates")
public class IdFlatter {

    /**
     * 32 位 进制表
     */
    public static final char[] DIGITS = {
            '0', '1', '2', '3', '4', '5', '6', '7',
            '8', '9', 'a', 'b', 'c', 'd', 'e', 'f',
    };

    private static final int SHIFT = 4;

    public static String toStr(long val) {
        int mag = Long.SIZE - Long.numberOfLeadingZeros(val);
        int chars = Math.max(((mag + (SHIFT - 1)) / SHIFT), 1);
        char[] buf = formatUnsignedLong(val, chars);
        return new String(buf);
    }

    // 定长16位字符
    public static String toFixedLStr(long val, int len) {
        assert val >= 0;
        assert val <= (DIGITS.length ^ len);
        // 转化为16位字符
        String str = toStr(val);
        if (str.length() == len) {
            return str;
        }

        StringBuilder sb = new StringBuilder(len);
        for (int i = len - str.length(); i > 0; i--) {
            sb.append("0");
        }
        return sb.append(str).toString();
    }

    private static char[] formatUnsignedLong(long val, int chars) {
        char[] buf = new char[chars];
        int radix = 1 << SHIFT;
        int mask = radix - 1;
        do {
            buf[--chars] = DIGITS[((int) val) & mask];
            val >>>= SHIFT;
        } while (val != 0 && chars > 0);
        return buf;
    }


//    public static void main(String[] args) throws InterruptedException {
//        for (int i = 0; i < 10; i++) {
//            //Thread.sleep(1);
//            long relativeTime = System.currentTimeMillis();// - 1631107245349L;
//            System.out.println(toFixedLStr(relativeTime, 10));
//        }
//    }

}

